package com.example.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.domain.dto.CommentDto;
import com.example.domain.dto.CommentQuery;
import com.example.domain.po.Comment;
import com.example.domain.response.PageResult;
import com.example.domain.vo.CommentVo;
import com.example.service.CommentService;
import com.example.mapper.CommentMapper;
import com.example.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
* @author adim
* @description 针对表【comment】的数据库操作Service实现
* @createDate 2025-06-16 01:54:44
*/
@Service
@RequiredArgsConstructor
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment>
    implements CommentService{


    private final CommentMapper commentMapper;
    private final UserService userService;
    /**
     * 添加评论
     * @param commentDto
     * @return
     */
    @Override
    public Integer addComment(CommentDto commentDto) {

        System.out.println("评论内容为"+commentDto.getContent());
        if(commentDto.getContent() == null){
            throw new RuntimeException("评论内容不能为空");
        }

        if(commentDto.getUserId() == null){
            throw new RuntimeException("用户ID不能为空");
        }
        Comment comment = new Comment();
        BeanUtil.copyProperties(commentDto, comment);

        comment.setCreateTime(LocalDateTime.now());
        comment.setStatus(1);
        System.out.println(comment.getUserId());
        Integer result = commentMapper.insertCommentByUserId(comment);

        return result;
    }

    /**
     * 分页查询
     * @param commentQuery
     * @return
     */
    @Override
    public PageResult<CommentVo> pageQuery(CommentQuery commentQuery) {

        Page<Comment> page = commentQuery.toMpPage();

        Page<Comment> commentPage = this.lambdaQuery()
                .eq(commentQuery.getStatus() != null, Comment::getStatus, commentQuery.getStatus())
                .page(page);
        List<CommentVo> commentList = commentPage.getRecords().stream()
                .map(comment -> {
                    Long userId =  comment.getUserId();
                    String username = userService.getUserNameById(userId);
                    CommentVo commentVo = new CommentVo();
                    BeanUtil.copyProperties(comment, commentVo);
                    commentVo.setUsername(username);
                    return commentVo;
                })
                .toList();
        //封装成PageResult
        PageResult<CommentVo> pageResult = new PageResult<>(commentPage.getTotal(),commentList);
        return pageResult;
    }
}




